package com.itbaizhan.service.impl;

import com.itbaizhan.dao.ItemDao;
import com.itbaizhan.pojo.Item;
import com.itbaizhan.pojo.LivegoodsBuyMessage;
import com.itbaizhan.result.BaseResult;
import com.itbaizhan.service.BuyactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.stereotype.Service;

/**
 * @author spf
 * @date 2024/3/6
 * @time 19:34
 */
@Service
public class BuyactionServiceImpl implements BuyactionService {

    @Autowired
    private ItemDao itemDao;
    @Autowired
    private StreamBridge streamBridge;
    @Value("${livegoods.cache.names.item.prefix}")
    private String itemPrefix;
    @Value("${livegoods.cache.names.item.suffix}")
    private String itemSuffix;

    @Override
    public BaseResult buyaction(String itemId, String user) {
        String key = itemPrefix + "::" + itemSuffix + "(" + itemId + ")";
        System.out.println(key);
        Item item = itemDao.get(key);
        if (item == null) {
            return new BaseResult(500, "页面开小差了！", null);
        } else {
            if (item.getIsRented()){
                return new BaseResult(500, "手慢了，已经被抢订了，预定失败", null);
            }
            LivegoodsBuyMessage livegoodsBuyMessage = new LivegoodsBuyMessage(itemId, user);
            boolean result = streamBridge.send("livegoodsMessage-out-0", livegoodsBuyMessage);
            if (result){
                return new BaseResult(200, "预定成功！", null);
            }else {
                return new BaseResult(500, "预定失败！", null);
            }
        }
    }
}
